package com.hs.sfzy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hs.sfzy.entity.Course;
import com.hs.sfzy.entity.Coursemark;
import com.hs.sfzy.entity.User;
import com.hs.sfzy.mapper.CourseMapper;
import com.hs.sfzy.mapper.CoursemarkMapper;
import com.hs.sfzy.mapper.UserMapper;
import com.hs.sfzy.service.CoursemarkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @ClassName CoursemarkServiceImpl
 * @Description 课程评价服务层
 * @Author shanglin
 * @Date 2024年10月24日 11:14
 * @Version 1.0
 */
@Service
public class CoursemarkServiceImpl implements CoursemarkService {
    @Autowired
    private CoursemarkMapper coursemarkMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Coursemark> selectAll(Coursemark coursemark) {
        return coursemarkMapper.selectAll(coursemark);
    }

    @Override
    public PageInfo<Coursemark> selectByPage(int pageNum, int pageSize, Coursemark coursemark) {
        PageHelper.startPage(pageNum,pageSize);
        List<Coursemark> coursemarks = coursemarkMapper.selectAll(coursemark);
        for(Coursemark cm : coursemarks){
            Long courseId = cm.getCourseId();
            Long userId = cm.getUserId();
            Course course = courseMapper.selectById(courseId);
            User user = userMapper.getUserById(userId);
            cm.setCourse(course);
            cm.setUser(user);
        }
        PageInfo<Coursemark> pageInfo = new PageInfo<Coursemark>(coursemarks);
        return pageInfo;
    }

    @Override
    public int deleteById(int id) {
        return coursemarkMapper.deleteById(id);
    }

    /**
     * 添加评价信息
     * @author QinKunPeng
     * @date 2024/10/29 9:13
     * @param coursemark
     * @return int
     */
    @Override
    public int insert(Coursemark coursemark) {
        int num = coursemarkMapper.insert(coursemark);
        courseMapper.updateCourseGrade(coursemark.getCourseId().intValue());
        return num;
    }

    // 根据课程id查评价
    @Override
    public List<Coursemark> selectByCourseId(Long courseId) {
        List<Coursemark> coursemarks = coursemarkMapper.selectByCourseId(courseId);
        for(Coursemark cm : coursemarks){
            cm.setUser(userMapper.getUserById(cm.getUserId()));
        }
        return coursemarks;
    }
}
